package com.sitech.openapi.service;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sitech.openapi.domain.customer.*;
import com.sitech.openapi.mapper.*;
import com.sitech.openapi.utils.DateUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class CustomerServiceImpl implements CustomerService {


    @Autowired
    private CustomerMapper customerMapper;
    @Autowired
    private PartyMapper partyMapper;
    @Autowired
    private PartyCertificationMapper partyCertificationMapper;
    @Autowired
    private PartyContactInfoMapper partyContactInfoMapper;
    @Autowired
    private CreditLimitMapper creditLimitMapper;

    @Override
    public Map<String, Object> getCustomerInfo(Map<String, Object> paraMap){

        log.info("入参信息：》》》》》》》》》"+paraMap.toString());
        Map<String,Object> resMap = new HashMap<>();

        String accNum = (String) paraMap.get("accNum");
        String certNum = (String) paraMap.get("certNum");
        String certType = (String) paraMap.get("certType");

        // 如果号码不是空的，按照号码查
        if (!StringUtils.isEmpty(accNum)) {
            resMap = getCustomerByAccNbr(paraMap);
        }else{
            // 否则按照证件号查
            if (!StringUtils.isEmpty(certNum) && !StringUtils.isEmpty(certType)){
                resMap = getCustomerByCertNumber(paraMap);
            }else{
                throw new RuntimeException("查询条件不能为空，号码和证件号码至少有一项！");
            }
        }

        return resMap;

    }

    /**
     * 根据号码查询客户信息
     * @param objectMap 号码，以及分页数据
     * @return 客户信息
     */
    public Map<String,Object> getCustomerByAccNbr(Map<String,Object> objectMap){

        Map<String,Object> resMap = new HashMap<>();
        List<Customer> customers = new ArrayList<>();

        String accNum = (String) objectMap.get("accNum");
        Integer pageSize = StringUtils.isEmpty(objectMap.get("pageSize"))?30:(Integer)objectMap.get("pageSize");
        Integer pageIndex = StringUtils.isEmpty(objectMap.get("pageIndex"))?1:(Integer)objectMap.get("pageIndex");

        PageHelper.startPage(pageIndex,pageSize);

        List<Cust> custs = customerMapper.queryCustInfoListByAccNbr(accNum);
        if( custs == null || custs.size() == 0) {
            throw new RuntimeException("根据号码未查询到客户信息，请核实号码是否存在！");
        }
        Page<Cust> page = (Page<Cust>) custs;

        customers = getCustomerByCust(custs);

        // 先将总数放进去
        resMap.put("total",page.getTotal());
        resMap.put("dataList",customers);
        return resMap;

    }

    /**
     * 根据号码查询客户信息
     * @param objectMap 证件号码和证件类型，以及分页数据
     * @return 客户信息
     */
    public Map<String,Object> getCustomerByCertNumber(Map<String,Object> objectMap){

        Map<String,Object> resMap = new HashMap<>();
        List<Customer> customers = new ArrayList<>();

        Map<String,String> paraMap = new HashMap<>();
        paraMap.put("certType",(String) objectMap.get("certType"));
        paraMap.put("certNum",(String) objectMap.get("certNum"));

        Integer pageSize = StringUtils.isEmpty(objectMap.get("pageSize"))?30:(Integer)objectMap.get("pageSize");
        Integer pageIndex = StringUtils.isEmpty(objectMap.get("pageIndex"))?1:(Integer)objectMap.get("pageIndex");
        PageHelper.startPage(pageIndex,pageSize);

        List<Cust> custs = customerMapper.queryCustInfoListByCertNum(paraMap);
        if( custs == null || custs.size() == 0) {
            throw new RuntimeException("根据证件号码未查询到客户信息，请核实证件信息是否正确！");
        }
        Page<Cust> page = (Page<Cust>) custs;

        customers = getCustomerByCust(custs);

        // 先将总数放进去
        resMap.put("total",page.getTotal());
        resMap.put("dataList",customers);
        return resMap;

    }

    /**
     * 根据客户信息查询customers实体对象信息
     * @param custs 客户实体列表
     * @return customers实体列表
     */
    public List<Customer> getCustomerByCust(List<Cust> custs){

        List<Customer> customers = new ArrayList<>();

        if (custs.size() > 0) {
            for (Cust cust : custs) {
                Customer customer = new Customer();

                // 查 party
                Party party = partyMapper.selectByPrimaryKey(cust.getPartyId());

                // 查 partyCertification
                PartyCertificationExample partyCertificationExample = new PartyCertificationExample();
                partyCertificationExample.createCriteria().andPartyIdEqualTo(cust.getPartyId());
                List<PartyCertification> partyCertifications = partyCertificationMapper.selectByExample(partyCertificationExample);
                PartyCertification partyCertification = new PartyCertification();
                if (partyCertifications != null && partyCertifications.size() > 0) {
                    partyCertification = partyCertifications.get(0);
                }

                // 查 party_contact_info
                PartyContactInfo partyContactInfo = new PartyContactInfo();
                PartyContactInfoExample contactInfoExample = new PartyContactInfoExample();
                contactInfoExample.createCriteria().andPartyIdEqualTo(cust.getPartyId());
                List<PartyContactInfo> partyContactInfos = partyContactInfoMapper.selectByExample(contactInfoExample);
                if (partyContactInfos != null && partyContactInfos.size() > 0) {
                    partyContactInfo = partyContactInfos.get(0);
                }
                List<ContactsInfo> contactsInfos = new ArrayList<>();
                ContactsInfo contactsInfo = new ContactsInfo();
                contactsInfo.setContactId(partyContactInfo.getContactId());
                contactsInfo.setExtContactId(partyContactInfo.getExtContactId());
                contactsInfo.setContactType(partyContactInfo.getContactType());
                contactsInfo.setContactName(partyContactInfo.getContactName());
                contactsInfo.setContactGender(partyContactInfo.getContactGender());
                contactsInfo.setContactAddr(partyContactInfo.getContactAddress());
                contactsInfo.setContactEmployer(partyContactInfo.getContactEmployer());
                contactsInfo.setHomePhone(partyContactInfo.getHomePhone());
                contactsInfo.setOfficePhone(partyContactInfo.getOfficePhone());
                contactsInfo.setMobilePhone(partyContactInfo.getMobilePhone());
                contactsInfo.setContactDesc(partyContactInfo.getContactDesc());
                contactsInfo.seteMail(partyContactInfo.geteMail());
                contactsInfo.setPostcode(partyContactInfo.getPostcode());
                contactsInfo.setPostAddr(partyContactInfo.getPostAddress());
                contactsInfo.setFax(partyContactInfo.getFax());
                contactsInfo.setStatusCd(partyContactInfo.getStatusCd());
                contactsInfo.setStatusDate(DateUtil.toStringYmdHmsWthH(partyContactInfo.getStatusDate()));
                //contactsInfo.setQqCode();
                //contactsInfo.setWxCode();
                //contactsInfo.setYxCode();
                //contactsInfo.setUnsuitableContactTime();

                // 查 creditLimit
                CreditLimit creditLimit = new CreditLimit();
                CreditLimitExample creditLimitExample = new CreditLimitExample();
                creditLimitExample.createCriteria().andCustIdEqualTo(cust.getCustId());
                List<CreditLimit> creditLimits = creditLimitMapper.selectByExample(creditLimitExample);
                if (creditLimits != null && creditLimits.size() > 0) {
                    creditLimit = creditLimits.get(0);
                }
                GCreditLimit GCreditLimit = new GCreditLimit();
                GCreditLimit.setCreditLimitId(creditLimit.getCreditLimitId());
                GCreditLimit.setExtCreditLimitId(creditLimit.getExtCreditLimitId());
                GCreditLimit.setObjType(creditLimit.getCreditObject());
                GCreditLimit.setObjId(creditLimit.getCreditObjectId());
                GCreditLimit.setExtObjId(creditLimit.getExtObjectId());
                GCreditLimit.setCreditLimitFee(creditLimit.getCreditLimitFee());
                GCreditLimit.setAvalableCreditLimitFee(creditLimit.getAvalableCreditLimitFee());
                //GCreditLimit.setEvaluateTime();
                GCreditLimit.setEvaluateType(creditLimit.getEvaluateType());
                GCreditLimit.setSetReason(creditLimit.getSetReason());
                GCreditLimit.setEffDate(DateUtil.toStringYmdHmsWthH(creditLimit.getEffectDate()));
                GCreditLimit.setExpDate(DateUtil.toStringYmdHmsWthH(creditLimit.getExpireDate()));
                GCreditLimit.setStatusCd(Long.parseLong(creditLimit.getFeeStatusCd()));
                GCreditLimit.setStatusDate(creditLimit.getStatusDate());
                GCreditLimit.setRemark(creditLimit.getRemark());


                List<PartyCert> partyCerts = new ArrayList<>();
                PartyCert partyCert = new PartyCert();
//                partyCert.setIsRealnameCert();
                partyCert.setCertType(partyCertification.getCertType());
                partyCert.setCertOrg(partyCertification.getCertOrg());
                partyCert.setCertAddr(partyCertification.getCertAddress());
                partyCert.setCertNum(partyCertification.getCertNumber());
                //partyCert.setChecker();
                //partyCert.setCheckTime();
                //partyCert.setCertCheckResult();
                partyCert.setEffDate(DateUtil.toStringYmdHmsWthH(partyCertification.getEffDate()));
                partyCert.setExpDate(DateUtil.toStringYmdHmsWthH(partyCertification.getExpDate()));
                partyCert.setStatusCd(party.getStatusCd());
                partyCert.setStatusDate(DateUtil.toStringYmdHmsWthH(party.getStatusDate()));
                //partyCert.setRemark();
                partyCerts.add(partyCert);
                customer.setPartyCerts(partyCerts);

                customer.setCustId(cust.getCustId());
                customer.setCustName(party.getPartyName());
                customer.setCustNumber(cust.getCustNumber());
                customer.setCustAddr(cust.getCustAddress());
                customer.setCustType(cust.getCustType());
                customer.setCustSubType(cust.getCustSubType());
                customer.setCustAreaGrade(cust.getCustAreaGrade());
                customer.setEnterDate(DateUtil.toStringYmdHmsWthH(cust.getEnterDate()));
//                customer.setIndustryTypeId();
                customer.setExtCustId(cust.getExtCustId());
                //customer.setSecrecyLevel();
                //customer.setCustControlLevel();
                //customer.setIsInstead();
                //customer.setIsRealname();
                customer.setStatusCd(cust.getStatusCd());
                customer.setStatusDate(DateUtil.toStringYmdHmsWthH(cust.getStatusDate()));
                customer.setRemark(cust.getRemarks());
                customer.setCreditLimit(GCreditLimit);
                //customer.setCredit();
                contactsInfos.add(contactsInfo);
                customer.setContactsInfos(contactsInfos);
                customer.setRegionId("8"+ cust.getLanId() +"00");
                customer.setPartyId(cust.getPartyId());
                // todo 纳税人表是从哪查
                //customer.setTaxPayerId();
                //customer.setCustAttrs();
                // todo 客户服务等级
                //customer.setServiceLevel();
                //customer.setCustLabel();

                customers.add(customer);
            }
        }

        return customers;
    }
}
